package com.choudou5.solr.service;

import com.choudou5.solr.annotation.ServiceInfo;
import com.choudou5.solr.bean.SearchHiBean;
import com.choudou5.solr.bean.common.*;
import com.choudou5.solr.util.GzipUtil;
import com.choudou5.solr.util.JsonUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.exception.BizException;
import com.choudou5.solr.util.thread.ThreadUtil;

import java.util.Date;
import java.util.List;

/**
 * @name 搜索历史 接口
 * @author choudou5
 * @date 2018-7-13
 */
@ServiceInfo(table = "solr_search_hi", desc = "搜索历史")
public class SearchHiService extends BaseService<SearchHiBean> {

    @Override
    public List<SearchHiBean> findList(SqlQueryBean sqlQueryBean) throws BizException {
        List<SearchHiBean> list = super.findList(sqlQueryBean);
//        if(CollUtil.isNotEmpty(list)){
//            for (SearchHiBean searchHiBean : list) {
//                //解压内容
//                searchHiBean.setResult(GzipUtil.uncompress(searchHiBean.getResult()));
//            }
//        }
        return list;
    }

    public void saveAsync(final SolrQueryParam queryParam, final String uid, final PageResult pageResult){
        if(StrUtil.isBlank(queryParam.getKeyword()) || queryParam.getKeyword().equals("*:*"))
            return;
        ThreadUtil.execAsync(new Runnable() {
            @Override
            public void run() {
                SearchHiBean hi = new SearchHiBean();
                hi.setModule(queryParam.getModule());
                hi.setKeyword(queryParam.getKeyword());
                hi.setQueryStr(queryParam.getQuery());
                hi.setNumFound(pageResult.getTotalCount());
                if(hi.getNumFound() > 0)//内容压缩存储
                    hi.setResult(GzipUtil.compress(JsonUtil.toStr(pageResult.getResult())));
                hi.setqTime(pageResult.getQt());
                hi.setCreateTime(new Date());
                hi.setStart(pageResult.getStart());
                hi.setUid(uid);
                add(hi);
            }
        });
    }

    public PageResult<GroupRespBean> stat(SqlQueryBean sqlQueryBean) throws BizException {
        String querySql = "SELECT keyword 'text', COUNT(1) num FROM "+getTable()+" WHERE keyword IS NOT NULL GROUP BY keyword ORDER BY num DESC " + sqlQueryBean.toLimitScript();
        String countSql = "SELECT COUNT(1) FROM(SELECT COUNT(1) FROM "+getTable()+" WHERE keyword IS NOT NULL GROUP BY keyword) T";
        PageBean pageBean = sqlQueryBean.getPageBean();
        PageResult<GroupRespBean> pageResult = new PageResult<>(pageBean);
        long count = countBySql(countSql);
        pageResult.setTotalCount(count);
        if(count > 0 && count > pageBean.getStart()){
            pageResult.setResult(findListMap(querySql));
        }
        return pageResult;
    }
}
